﻿@using DCMS.ViewModel.Models.Sales;
@model ExchangeBillModel

<script type="text/javascript">

	jQuery(document).ready(function () {
		"use strict";
		// Init Theme Core
		Core.init({
			sbm: "sb-l-c",
		});
		// Init Demo JS
		Demo.init();

        var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
        if (model.ReversedStatus) {
            $("#inkpadBox").hide();
            $("#inkpadBox1").css('display', 'block');
        }
		if (model.AllowSelectionDateRange > 0) {
			var maxDate = $(this).dateFtt("yyyy-MM-dd", new Date());
			var minDate = new Date(maxDate).setDate(new Date(maxDate).getDate() - model.AllowSelectionDateRange);
			minDate = $(this).dateFtt("yyyy-MM-dd", new Date(minDate));

			$('#datetimepicker_TransactionDate').data("DateTimePicker").maxDate(maxDate);
			$('#datetimepicker_TransactionDate').data("DateTimePicker").minDate(minDate);
		}


		/*
		 * ======================================================
		 * mschen 2018-12-5 11:24:43 begin
		 * ======================================================
		 */

        //获取备注
        var rdata = { "100": "临期换货" };
        var remarkConfigs = new Array();
        var ks = Object.keys(rdata);
        var vs = Object.values(rdata);
        ks.forEach(function (a, b) {
            var remarkConfit = {};
            remarkConfit.Id = a;
            remarkConfit.Name = vs[b];
            remarkConfigs.push(remarkConfit);
        });

		//审核
		$("#btn_auditing").click(function () {
			//防止重复保存
			var loadingButton = Ladda.create(this);
            loadingButton.start();
            var returnUrl = "@Context.Request.Query["returnURL"]";
            if (returnUrl.indexOf("AuditedStatus=") == -1) {
                if (returnUrl.indexOf("?") == -1) {
                    returnUrl += "?";
                } else {
                    returnUrl += "&";
                }
                returnUrl += "AuditedStatus=False";
            } else {
                if (returnUrl.indexOf("AuditedStatus=False") == -1) {
                    returnUrl = returnUrl.replace("AuditedStatus=", "AuditedStatus=False");
                }
            }
            returnUrl = returnUrl.replace(/amp;/g, "");
            $(this).remoteSubmit("get", "/ExchangeBill/Auditing", { id: "@Model.Id" }, null, function () { location.href = returnUrl; }, null, loadingButton);
		});

		//红冲
		$("#btn_red").click(function () {
			//防止重复保存
			var loadingButton = Ladda.create(this);
			WinMsg.confirm({ message: "确认要红冲吗？" }).on(function (e) {
				if (!e) {
					return;
				}
				loadingButton.start();
				$(this).remoteSubmit("get", "/ExchangeBill/Reverse", { id: "@Model.Id" }, null, function () { location.href = "/ExchangeBill/List"; }, null, loadingButton);
			});
        });

        //作废
        $("#btn_cancel").click(function () {
			//防止重复保存
			var loadingButton = Ladda.create(this);

			WinMsg.confirm({ message: "确认要作废吗？" }).on(function (e) {
				if (!e) {
					return;
				}
				loadingButton.start();
                $(this).remoteSubmit("get", "/ExchangeBill/Delete", { id: "@Model.Id" }, null, function () { location.href = "/ExchangeBill/List"; }, null, loadingButton);
			});
		});

		//打印
		$("#btn_print").click(function () {
			//防止重复保存
			var loadingButton = Ladda.create(this);
			WinMsg.confirm({ message: "确认要打印吗？" }).on(function (e) {
				if (!e) {
					return;
				}
                loadingButton.start();
                var setting = {}
                var LODOP = null;
                var rs = $(this).getSyncData("/ExchangeBill/PrintSetting", null, "get");
                if (rs.Success) {
                    setting = rs.Data;
                    loadCLodop(document, setting.PrintPort, () => {
                        //判断页面是否已加载LODOP
                        if (LODOP == null || LODOP == undefined) {
                            LODOP = getLodopFirst(document);
                            LODOP = getLodopSecond(document);
                        }
                        if (LODOP == null || LODOP == undefined) {
                            loadingButton.stop();
                            return;
                        } else {
                            $("#printData").html("");
                        }
                        $(this).remoteSubmit("get", "/ExchangeBill/Print", { selectData: "@Model.Id" }, null, function (result) {
                            if (result.Success) {
                                var html = result.Data;
                                LODOP.PRINT_INIT("换货单");
                                if (!isNaN(setting.PaperWidth) && !isNaN(setting.PaperHeight)) {
                                    LODOP.SET_PRINT_PAGESIZE(1, setting.PaperWidth + "mm", setting.PaperHeight + "mm");
                                }
                                if (setting.IsPrintPageNumber) {
                                    LODOP.ADD_PRINT_HTM(1, 600, 300, 100, "总页号：<font color='#0000ff' format='ChineseNum'><span tdata='pageNO'>第##页</span>/<span tdata='pageCount'>共##页</span></font>");
                                }
                                if (!isNaN(setting.MarginTop) && !isNaN(setting.MarginLeft) && !isNaN(setting.MarginRight) && !isNaN(setting.MarginBottom)) {
                                    LODOP.ADD_PRINT_HTM(setting.MarginTop + "mm", setting.MarginLeft + "mm", "RightMargin:" + setting.MarginRight + "mm", "BottomMargin:" + setting.MarginBottom + "mm", html);
                                }
                                LODOP.SET_PRINT_STYLEA(0, "Horient", 2);
                                LODOP.PREVIEW(true);
                                loadingButton.stop();
                            }
                            else {
                                $(this).showToastr(result.Message);
                            }
                        }, null, loadingButton);
                    });
                }

			});
		});

		//选择终端
		$(document).on('click', "#btn_search_customer", function () {
			var actionUrl = "/Terminal/AsyncSearchSelectPopup";
			$(this).showModalV2($("#TerminalSelectModalWindow"), actionUrl, { ids: "" }, "选择终端", $("#TerminalSelectForm"), function (rows) { });
		});
		//选择终端绑定事件
		window.operateEventsPopTerminal = {
            'click .rowSelect': function (e, value, row, index)
            {
                try
                {
                    var businessUserId = $("#BusinessUserId").val();

                    //检查是否需要提供赠品
                    $(this).remoteRequest('GET', '/Terminal/CheckTerminalHasGives', {
                        terminalId: row.Id,
                        businessUserId: businessUserId
                    },
                        function (data) {
                            if (data.HasGives) {
                                $("#GiveQuotaSelectBox").show();
                            }
                            else {
                                $("#GiveQuotaSelectBox").hide();
                            }
                        });

                    $("#ChannelId").val(row.ChannelId);
                    $("#TerminalId").val(row.Id);
					$("#TerminalName").val(row.Name);
					$('#TerminalSelectModalWindow').modal('hide');
				}
                catch (err)
                {
					console.log(err);
					$(this).showToastr(err);
					return;
				}
			}
		};

		//商品列表选择赋值
		window.operateEventsPop = {
			'click .rowSelect': function (e, value, row, index) {
				try {

					var index = $(this).attr("data-id");
					var wareHouseId = $("#WareHouseId").val();
					var terminalId = $("#TerminalId").val();

					//获取商品详细信息

                    var keys = Object.keys(row.Units);
                    var isMinUnitSale = $("#IsMinUnitSale").val();
                    var dateKeys = Object.keys(row.ProductTimes);

                    //1.初始商品单位
                    //初始最小单位单位
                    var unitId = row.SmallUnitId;
                    var unitName = keys[0];
                    //如果不是最小单位
                    if (isMinUnitSale != "1" && isMinUnitSale != "True") {
                        //有大单位赋值大单位
                        if (row.BigUnitId != null && row.BigUnitId != 0) {
                            unitId = row.BigUnitId;
                            unitName = keys[2];
                        } else {
                            //有中单位赋值中单位
                            if (row.StrokeUnitId != null && row.StrokeUnitId != 0) {
                                unitId = row.StrokeUnitId;
                                unitName = keys[1];
                            }
                        }
                    }

                    //成本价
                    var costPrice = 0;
                    var ck = Object.keys(row.CostPrices);
                    var cv = Object.values(row.CostPrices);
                    ck.forEach(function (a, b) {
                        if (a == unitId) {
                            costPrice = cv[b];
                        }
                    });

                    //2.初始商品价格、参考价格
                    var referPrices; //参照价格
                    var defaultAmountId = $("#DefaultAmountId").val();
                    //默认价格
                    var prices;
                    //如果此商品有价格体系
                    row.ProductTierPrices.forEach(function (a, b) {
                        var planIdTypeId = a.PricesPlanId + "_" + a.PriceTypeId;
                        if (defaultAmountId == planIdTypeId) {
                            if (unitId == row.SmallUnitId) {
                                prices = a.SmallUnitPrice;
                                if (model.VariablePriceCommodity == 0) {
                                    referPrices = a.SmallUnitPrice;
                                }
                            }
                            else if (unitId == row.StrokeUnitId) {
                                prices = a.StrokeUnitPrice;
                                if (model.VariablePriceCommodity == 0) {
                                    referPrices = a.StrokeUnitPrice;
                                }
                            }
                            else if (unitId == row.BigUnitId) {
                                prices = a.BigUnitPrice;
                                if (model.VariablePriceCommodity == 0) {
                                    referPrices = a.BigUnitPrice;
                                }
                            }
                        }
                    });

                    //3.参考批发价格
                    if (model.VariablePriceCommodity !== 0) {
                        if (unitId == row.SmallUnitId) {
                            referPrices = row.Prices[0].ProductPrice.TradePrice;
                        }
                        else if (unitId == row.StrokeUnitId) {
                            referPrices = row.Prices[1].ProductPrice.TradePrice;
                        }
                        else if (unitId == row.BigUnitId) {
                            referPrices = row.Prices[2].ProductPrice.TradePrice;
                        }
                    }

                    //4.库存数量
                    var stockQty = 0;
                    var actualQty = 0;
                    var unableQty = 0;

                    //仓库Id
                    var wareHouseId = $("#WareHouseId").val();
                    row.StockQuantities.forEach(function (a, b) {
                        if (a.WareHouseId == wareHouseId) {
                            stockQty = model.APPShowOrderStock == true ? a.CurrentQuantity : a.UsableQuantity;
                            actualQty = a.UsableQuantity;
                            unableQty = a.CurrentQuantity - a.UsableQuantity;
                        }
                    });

					$("#ExchangeItems").bootstrapTable('updateRow', {
								index: index, row: {
									ProductSKU: row.Sku,
									ProductId: row.Id,
									ProductName: row.Name,
									BarCode: row.SmallBarCode,
									UnitConversion: row.UnitConversion,
									ProductTimes: row.ProductTimes,
									IsManufactureDete: row.IsManufactureDete,
									ManufactureDete: dateKeys[0],
									Units: row.Units,
									UnitId: unitId,
									UnitName: unitName,
									Price: prices,
									Quantity: 0,
									Amount: 0,
									CostPrices: row.CostPrices,
									CostPrice: costPrice,
									CostAmount: 0,
									Prices: row.Prices,
									ProductTierPrices: row.ProductTierPrices,  //价格体系
									StockQty: stockQty,
									UnabledStockQty: unableQty,
									StockQuantity: actualQty,
									StockQuantities: row.StockQuantities, //库存数量
									BigQuantity: row.BigQuantity,//大转小
									StrokeQuantity: row.StrokeQuantity,//中转小
									SmallUnitId: row.SmallUnitId,  //小单位
									StrokeUnitId: row.StrokeUnitId,  //中单位
									BigUnitId: row.BigUnitId,  //大单位
									IsAdjustPrice: row.IsAdjustPrice, //是否允许改价
									ReferPrices: referPrices, //参照价格
									IsFlavorProduct: row.IsFlavor, //商品口味
									Profit: 0, //利润
									CostProfitRate: 0, //成本利润率
									TaxRate: "@Model.TaxRate", //税率%
									ContainTaxPrice: 0, //含税价格
									TaxPrice: 0, //税额
									TaxPriceAmount: 0 //税价总计
								}
							});
					//$("#ExchangeItems").bootstrapTable('refresh');
					$('#ModalProductWindows').modal('hide');
				}
				catch (err) {
					console.log(err);
					$(this).showToastr(err);
					return;
				}
			}
		};

		//获取预收金额
        function SumAdvanceReceiptAmount() {
            var sumAdvanceReceiptAmount = 0;
            var colls = $("input[name='CollectionAmount']");
            for (var i = 0; i < colls.length; i++) {
                if ($(colls[i]).attr("data-codetype") == 24) {
                    if (isNaN($(colls[i]).val()) || $(colls[i]).val() == "") {
                        $(colls[i]).val("0.00")
                    }
                    sumAdvanceReceiptAmount = parseFloat(sumAdvanceReceiptAmount) + parseFloat(colls[i].value);
                }
            }
            return sumAdvanceReceiptAmount;
        }
		//表单检查
		var formValidator = function () {
			var isVaild = true;
			if ($("#TerminalId").val() == "" || $("#TerminalId").val() == "0") {
				$("#TerminalId").focus();
				$(this).showToastr("请先选择客户！");
				return false;
			}
			else if ($("#BusinessUserId").val() == "") {
				$("#BusinessUserId").focus();
				$(this).showToastr("请先选择业务员！");
				return false;
			}
			else if ($("#WareHouseId").val() == "") {
				$("#WareHouseId").focus();
				$(this).showToastr("请先选择仓库！");
				return false;
			}
			else if ($("input[name='TransactionDate']").val() == "") {
				$("input[name='TransactionDate']").focus();
				$(this).showToastr("请先选择交易日期！");
				return false;
			}
			return isVaild;
		}

		//换货单项目
        $("#ExchangeItems").bootstrapTable({
			@if (Model.Items.Count > 0 && Model.SaleReservationBillId==0)
            {
				@Html.Raw("url: '/ExchangeBill/AsyncExchangeItems?exchangeBillId=" + Model.Id + "&orderId=0',")
            }
            else if (Model.SaleReservationBillId > 0)
            {
               @Html.Raw("url: '/ExchangeBill/AsyncExchangeItems?exchangeBillId=0&orderId=" + Model.SaleReservationBillId + "',")
            }
            else
            {
                @Html.Raw("length: 9,")
            }
            striped: true,
            cache: false,
            pagination: true,
            showPagination: false,
            sidePagination: "server",
            sortable: false,
            sortOrder: "asc",
            search: false,
            strictSearch: false,
            showColumns: false,
            showRefresh: false,
            clickToSelect: false,
            uniqueId: "id",
            showToggle: false,
            editable: true,
            cardView: false,
            detailView: false,
            showFooter: true,
            onLoadSuccess: function (data) {
                $(".fixed-table-pagination").hide();

            },
            onPostBody: function (data) {
                $("[data-toggle='popover']").popover();
            },
            columns: [

                {
                    title: '<i class="fa fa-gear fs18"></i>',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return m_pagerow + index + 1;
                    },
                    footerFormatter: function (value) {
                        return '总计';
                    }
                },
                {
                    field: 'ProductCode',
                    title: '商品编号',
                    align: 'center', visible: false

                },
                { field: 'UnitId', visible: false },
                { field: 'Units', visible: false },
                { field: 'Prices', visible: false },
                { field: 'ProductTierPrices', visible: false },  //价格体系
                { field: 'SmallUnitId', visible: false }, //小单位
                { field: 'StrokeUnitId', visible: false }, //中单位
                { field: 'BigUnitId', visible: false }, //大单位

                { field: 'ProductId', visible: false },
                { field: 'IsAdjustPrice', visible: false },
                { field: 'ReferPrices', visible: false }, //参照价格
                {
                    field: 'ProductName',
                    title: '更换商品',
                    width: '300',
                    align: 'center',
                    formatter: function (value) {
                        return (value == 0 || value == "" || value == undefined) ? "" : @Model.Id== 0 ? $(this).cutString(value, 50) : "<a style='color:black; text-decoration:none;'  data-trigger='hover' title='' data-container='body' data-toggle='popover' data-placement='top' data-content='" + value + "'>" + $(this).cutString(value, 50) + "</a>";
                    }
                },
                {
                    field: 'SmallBarCode',
                    title: '条形码',
                    align: 'center',
                    formatter: $(this).formatIsNull

                },
                {
                    field: 'UnitName',
                    title: '单位',
                    align: 'center'
                    ,
                    formatter: $(this).formatIsNull

                },
                {
                    field: 'UnitConversion',
                    title: '单位换算',
                    align: 'center'
                    ,
                    formatter: $(this).formatIsNull

                },
                {
                    field: 'Quantity',
                    align: 'center',
                    width: '100',
                    title: '换货数量',
                    formatter: function (value, row, index) {
                        if (Object.keys(row).length > 1) {
                            return (value == 0 || value == "") ? "" : value + "" + row.UnitName + (row.IsFlavorProduct ? "<span style='color:darkorange' class='mt5'>  口</span>" : "");
                        }
                        else {
                            return (value == 0 || value == "" || value == undefined) ? "" : value
                        }
                    }
                },
                { field: 'IsManufactureDete', visible: false },  //该商品是否开启生产日期功能
                { field: 'IsFlavorProduct', visible: false },
                { field: 'FlavorId', visible: false },
                { field: 'ProductTimes', visible: false },
                {
                    field: 'ManufactureDete',
                    title: '生产日期',
                    visible: model.IsShowCreateDate,
                    align: 'center',
                    visible: true

                },
                {
                    field: 'Price',
                    title: '当前价格',
                    width: '100',
                    formatter: function (value, row, index) {
                        if (Object.keys(row).length > 1) {

                            value = $(this).formatFixed(value);
                            //if (value == 0) value = 0.00;

                            if (row.ReferPrices && row.ReferPrices != "" && row.ReferPrices != null) {
                                if (value != "" && value != row.ReferPrices) {
                                    return "<span alt=" + value + " style='color:#f34a70;'>" + value + "</span>";
                                }
                                else {
                                    return value;
                                }
                            }
                            else {
                                if (value != "" && value != row.Prices[0].ProductPrice.TradePrice) {
                                    return "<span alt=" + value + " style='color:#f34a70;'>" + value + "</span>";
                                }
                                else {
                                    return value;
                                }
                            }
                        }
                        else {
                            return (value == 0 || value == "" || value == undefined) ? "" : value;
                        }
                    },
                    align: 'center'

                },
                { field: 'CostPrices', visible: false },
                {
                    field: 'CostPrice',
                    title: '成本价', visible: false, align: 'right', formatter: $(this).formatFixed

                },
                {
                    field: 'CostAmount',
                    title: '成本金额', visible: false, align: 'right', formatter: $(this).formatFixed

                },
                {
                    field: 'Amount',
                    title: '金额',
                    width: '100',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return (value == 0 || value == "" || value == undefined) ? "" : model.AuditedStatus == true ? value : parseFloat(value).toFixed(2);
                    },
                    footerFormatter: function (value) {
                        var count = $(this).alculateTaxAmountSub('@Model.Id', '@Model.AuditedStatus', '#ExchangeItems', '@Model.EnableTaxRate', value);

                        var total = parseFloat((typeof (count) == 'undefined' || count == "") ? '0' : count);

                        var otherAmount = 0;
                        var accounts = $("#ExchangeItems_Partial_Form").find("input[name='CollectionAmount']");
                        $.each(accounts, function (i, input) {
                            var option = $(input).attr("data-account");
                            var amount = $(input).val();
                            if ($("#CollectionAccount").val() !== option) {
                                otherAmount += amount;
                            }
                        });

                        $("#SumAmount").val(total);

                        return total.toFixed(2);
                    }
                },
                {
                    field: 'UnabledStockQty',
                    title: '预占库存',
                    align: 'center',
                    width: '100',
                    formatter: function (value, row, index) {

                        if (value != "" && value != undefined && row.ProductId != "" && row.ProductId > 0) {

                            var bigUnitId = row.BigUnitId;
                            var bigUnitName = "";

                            var strokeUnitId = row.StrokeUnitId;
                            var strokeUnitName = "";

                            var smallUnitId = row.SmallUnitId;
                            var smallUnitName = "";

                            $.each(row.Units, function (key, unit) {
                                if (unit == bigUnitId) {
                                    bigUnitName = key;
                                }
                                else if (unit == strokeUnitId) {
                                    strokeUnitName = key;
                                }
                                else if (unit == smallUnitId) {
                                    smallUnitName = key;
                                }
                            });

                            //计算结果数量
                            var resultQuantity = value;
                            //大单位计算结果
                            var big = parseInt(resultQuantity / row.BigQuantity);
                            resultQuantity = resultQuantity - big * row.BigQuantity;
                            //中单位计算结果
                            var stroke = 0;
                            if (strokeUnitId > 0 && row.StrokeQuantity > 0) {
                                stroke = parseInt(resultQuantity / row.StrokeQuantity);
                                resultQuantity = resultQuantity - stroke * row.StrokeQuantity;
                            }
                            //小单位计算结果
                            var small = resultQuantity;

                            var content = big + "" + bigUnitName;

                            if (stroke > 0)
                                content += ((strokeUnitId > 0) ? (stroke + "" + strokeUnitName) : "");

                            if (small > 0)
                                content += small + "" + smallUnitName


                            return "<span alt=" + value + ">" + content + "</span>";

                        }
                        else {
                            return "";
                        }
                    },
                    visible: model.APPShowOrderStock

                },
                {
                    field: 'StockQuantity',
                    title: '可用库存',
                    align: 'center',
                    width: '100',
                    formatter: function (value, row, index) {

                        if (value != "" && value != undefined && row.ProductId != "" && row.ProductId > 0) {

                            var bigUnitId = row.BigUnitId;
                            var bigUnitName = "";

                            var strokeUnitId = row.StrokeUnitId;
                            var strokeUnitName = "";

                            var smallUnitId = row.SmallUnitId;
                            var smallUnitName = "";

                            $.each(row.Units, function (key, unit) {
                                if (unit == bigUnitId) {
                                    bigUnitName = key;
                                }
                                else if (unit == strokeUnitId) {
                                    strokeUnitName = key;
                                }
                                else if (unit == smallUnitId) {
                                    smallUnitName = key;
                                }
                            });

                            //计算结果数量
                            var resultQuantity = value;
                            //大单位计算结果
                            var big = parseInt(resultQuantity / row.BigQuantity);
                            resultQuantity = resultQuantity - big * row.BigQuantity;
                            //中单位计算结果
                            var stroke = 0;
                            if (strokeUnitId > 0 && row.StrokeQuantity > 0) {
                                stroke = parseInt(resultQuantity / row.StrokeQuantity);
                                resultQuantity = resultQuantity - stroke * row.StrokeQuantity;
                            }
                            //小单位计算结果
                            var small = resultQuantity;

                            var content = big + "" + bigUnitName;

                            if (stroke > 0)
                                content += ((strokeUnitId > 0) ? (stroke + "" + strokeUnitName) : "");

                            if (small > 0)
                                content += small + "" + smallUnitName


                            return "<span alt=" + value + ">" + content + "</span>";
                        }
                        else {
                            return "";
                        }
                    },
                    visible: model.APPShowOrderStock

                },
                {
                    field: 'StockQty',
                    title: model.APPShowOrderStock == false ? '库存数量' : '实际库存',
                    align: 'center',
                    width: '100',
                    formatter: function (value, row, index) {

                        if (value != "" && row.ProductId != "" && row.ProductId > 0) {

                            var bigUnitId = row.BigUnitId;
                            var bigUnitName = "";

                            var strokeUnitId = row.StrokeUnitId;
                            var strokeUnitName = "";

                            var smallUnitId = row.SmallUnitId;
                            var smallUnitName = "";

                            $.each(row.Units, function (key, unit) {
                                if (unit == bigUnitId) {
                                    bigUnitName = key;
                                }
                                else if (unit == strokeUnitId) {
                                    strokeUnitName = key;
                                }
                                else if (unit == smallUnitId) {
                                    smallUnitName = key;
                                }
                            });

                            //计算结果数量
                            var resultQuantity = value;
                            //大单位计算结果
                            var big = parseInt(resultQuantity / row.BigQuantity);
                            resultQuantity = resultQuantity - big * row.BigQuantity;
                            //中单位计算结果
                            var stroke = 0;
                            if (strokeUnitId > 0 && row.StrokeQuantity > 0) {
                                stroke = parseInt(resultQuantity / row.StrokeQuantity);
                                resultQuantity = resultQuantity - stroke * row.StrokeQuantity;
                            }
                            //小单位计算结果
                            var small = resultQuantity;

                            var content = big + "" + bigUnitName;

                            if (stroke > 0)
                                content += ((strokeUnitId > 0) ? (stroke + "" + strokeUnitName) : "");

                            if (small > 0)
                                content += small + "" + smallUnitName


                            return "<span alt=" + value + ">" + content + "</span>";
                        }
                        else {
                            return "";
                        }
                    }
                },
                {
                    field: 'Remark',
                    title: '备注',
                    align: 'center',
                    width: '150',
                    formatter: $(this).formatIsNull

                },
                {
                    field: 'Operate',
                    title: '操作',
                    align: 'center',
                    width: '130',
                    events: {
                        'click .rowAppend': function (e, value, row, index) {
                            // 添加
                            //审核、红冲后不能修改
                            if ("@Model.AuditedStatus" == "True" || "@Model.ReversedStatus" == "True") {
                                return false;
                            }
                            $('#ExchangeItems').bootstrapTable('insert', row);
                            //修改最后一条数据uniqueid,防止复制时uniqueid相同，删除时都删除
                            var allTableData = $('#SaleItems').bootstrapTable('getData');
                            var maxuniqueid = 0;
                            $.each(allTableData, function (i, row) {
                                if (row.uniqueid > maxuniqueid) {
                                    maxuniqueid = row.uniqueid;
                                }
                            });
                            allTableData[allTableData.length - 1].uniqueid = maxuniqueid + 1;
                            allTableData[allTableData.length - 1].Id = 0;
                        },
                        'click .rowCopy': function (e, value, row, index) {// 复制
                            //审核、红冲后不能修改
                            if ("@Model.AuditedStatus" == "True" || "@Model.ReversedStatus" == "True" || row.SaleProductTypeId == 2) {
                                return false;
                            }
                            $('#ExchangeItems').bootstrapTable('copying', row);
                            //修改最后一条数据uniqueid,防止复制时uniqueid相同，删除时都删除
                            var allTableData = $('#ExchangeItems').bootstrapTable('getData');
                            var maxuniqueid = 0;
                            $.each(allTableData, function (i, row) {
                                if (row.uniqueid > maxuniqueid) {
                                    maxuniqueid = row.uniqueid;
                                }
                            });
                            allTableData[allTableData.length - 1].uniqueid = maxuniqueid + 1;
                            allTableData[allTableData.length - 1].Id = 0;
                            allTableData[allTableData.length - 1].IsGifts = false;
                        },
                        'click .rowDel': function (e, value, row, index) {
                            // 删除
                            //审核、红冲后不能修改
                            if ("@Model.AuditedStatus" == "True" || "@Model.ReversedStatus" == "True") {
                                return false;
                            }
                            var datas = $('#ExchangeItems').bootstrapTable('getData');
                            var len = datas.length;
                            if (len == 1) {
                                $(this).showToastr('数据不能删除');
                                return;
                            }

                            if (row.uniqueid == undefined) {
                                $("#ExchangeItems").bootstrapTable('remove', { field: "Id", values: [parseInt(row.Id)] });
                            }
                            else {
                                $("#ExchangeItems").bootstrapTable('remove', { field: "uniqueid", values: [parseInt(row.uniqueid)] });
                            }
                        }
                    },
                    formatter: function (value, row, index) {
                        return [
                            '<button type="button" class="btn btn-sm btn-default rowAppend" title="添加"><i class="fa fa-plus" ></i></button>',
                            '<button type="button" class="btn btn-sm btn-default rowCopy" title="复制"><i class="fa fa-copy" ></i></button>',
                            '<button type="button" class="btn btn-sm btn-default rowDel" title="删除"><i class="fa fa-trash-o"></i></button>'
                        ].join('');
                    }
                }
            ],
            onClickCell: function (field, value, row, $element) {

                if (field == "Operate") {
                    return false;
                }

                var input = $($element).find("input");
                var select = $($element).find("select");
                if (input.length > 0 || select.length > 0)
                    return false;

                //当前列所在行的索引
                var index = $element.parent().attr("data-index");

                //审核、红冲后不能修改
                if ("@Model.AuditedStatus" == "True" || "@Model.ReversedStatus" == "True") {
                    return false;
                }

                //验证无效或者单据已经审核则不允许修改编辑
                if (!formValidator() || $("#AuditedStatus").val() == "True") {
                    return false;
                }

                if (field == "ProductName") {
                    //促销活动赠送商品不允许修改  SaleProductTypeEnum 这个枚举
                    if (row.SaleProductTypeId == 2 && field != "Remark") {
                        return false;
                    }
                    var html = '<div class="input-group">' +
                        '<input type="text" class="form-control input-sm"  name="ProductName" value="' + (typeof (value) == 'undefined' ? "" : value) + '" id="' + field + "_" + row.Id + '">' +
                        '<span class="input-group-btn"><button class="btn btn-default btn-sm searchproduct" id="search_' + field + "_" + row.Id + '" data-index="' + index + '"><span class="glyphicon glyphicon-search"></span></button></span>' +
                        '</div>';

                    $($element).html(html);
                    var inputObj = $("#search_" + field + "_" + row.Id);
                    inputObj.focus();
                    inputObj.select();
                    inputObj.bind("focusout", function () {
                        $("#ExchangeItems").bootstrapTable('updateRow', { index: index, row: { ProductName: value } });
                        $($element).html("" + value + "");
                    });
                    //选择商品
                    inputObj.bind("click", function () {
                        var wareHouseId = $("#WareHouseId").val();
                        var terminalId = $("#TerminalId").val();
                        $(this).productSelectShowModal($("#ModalProductWindows"), "/Product/AsyncSearchSelectPopup?wareHouseId=" + wareHouseId + "&stockQtyMoreThan=true&includeProductDetail=0&terminalId=" + terminalId, { Index: $(this).attr("data-index") }, "选择商品", $("#ProductModalForm"),
                            function () { });
                        return false;

                    });
                }
                else if (["Price", "Quantity"].indexOf(field) >= 0) {
                    var html = '<input type="text" class="form-control input-sm onlyNum" value="' + (typeof (value) == 'undefined' ? "0" : value) + '" id="' + field + "_" + row.Id + '">';

                    if (field == "Price" || field == "Quantity") {
                        if (field == "Price") {
                            //允许变更价格
                            $($element).html(html);
                            var inputObj = $("#" + $(html).attr("id"));

                            inputObj.focus();
                            inputObj.select();

                            inputObj.bind("focusout", function () {
                                if ($(this).val() == "") {
                                    $(this).val(0);
                                }
                                row[field] = parseFloat($(this).val());
                                $("#ExchangeItems").bootstrapTable('updateRow', { index: index, row: row });
                                $($element).html("" + value + "");
                            });

                            inputObj.bind("change", function () {
                                if (!isNaN($(this).val())) {
                                    if ($(this).val() == "") {
                                        $(this).val(0);
                                    }
                                    var oldQuantity = row.Quantity;
                                    row.Price = $(this).val();
                                    var newAmount = $(this).floatTimes(parseFloat($(this).val()), oldQuantity);
                                    row.Amount = newAmount;

                                    //成本金额
                                    row.CostAmount = $(this).floatTimes(oldQuantity, row.CostPrice);
                                    //含税价格
                                    row.ContainTaxPrice = $(this).floatTimes(parseFloat((1 + row.TaxRate / 100)), row.Price);
                                    //利润
                                    row.Profit = row.TaxPriceAmount - row.CostAmount;
                                    //成本利润率
                                    if (row.CostAmount == 0) {
                                        row.CostProfitRate = 100;
                                    } else {
                                        row.CostProfitRate = row.Profit / row.CostAmount * 100;
                                    }

                                    //格式化(先计算，再格式化，不然数据不准)
                                    row.Amount = parseFloat(row.Amount).toFixed(2);
                                    row.CostAmount = parseFloat(row.CostAmount).toFixed(2);
                                    row.ContainTaxPrice = parseFloat(row.ContainTaxPrice).toFixed(2);
                                    row.TaxPrice = parseFloat(row.TaxPrice).toFixed(2);
                                    row.TaxPriceAmount = parseFloat(row.TaxPriceAmount).toFixed(2);
                                    row.Profit = parseFloat(row.Profit).toFixed(2);
                                    row.CostProfitRate = parseFloat(row.CostProfitRate).toFixed(2);

                                }
                                else {
                                    $(this).val(0);
                                    $(this).showToastr("只能输入数字!");
                                }
                            });
                        }

                        if (field == "Quantity") {

                            $($element).html(html);
                            var inputObj = $("#" + $(html).attr("id"));

                            inputObj.focus();
                            inputObj.select();

                            inputObj.bind("focusout", function () {
                                if ($(this).val() == "") {
                                    $(this).val(0);
                                }
                                //数量转整数
                                row[field] = parseInt($(this).val());
                                $("#ExchangeItems").bootstrapTable('updateRow', { index: index, row: row });
                                $($element).html("" + value + "");
                            });

                            inputObj.bind("change", function () {
                                if (!isNaN($(this).val())) {
                                    if ($(this).val() == "") {
                                        $(this).val(0);
                                    }
                                    //数量转整数
                                    row.Quantity = parseInt($(this).val());

                                    if (row.IsGifts == false) {
                                        var oldPrice = row.Price;
                                        var newAmount = $(this).floatTimes(parseInt($(this).val()), oldPrice);
                                        row.Amount = newAmount;

                                        //成本金额
                                        row.CostAmount = $(this).floatTimes(parseInt($(this).val()), row.CostPrice);
                                        //含税价格
                                        row.ContainTaxPrice = $(this).floatTimes(parseFloat((1 + row.TaxRate / 100)), row.Price);
                                        //税额
                                        row.TaxPrice = $(this).floatTimes($(this).floatTimes(parseFloat(row.TaxRate / 100), row.Price), row.Quantity);
                                        //价税总计
                                        if ('@Model.EnableTaxRate' == 'True') {
                                            row.TaxPriceAmount = $(this).floatTimes(row.ContainTaxPrice, row.Quantity);
                                        }
                                        else {
                                            row.TaxPriceAmount = $(this).floatTimes(row.Price, row.Quantity);
                                        }

                                        //利润
                                        row.Profit = row.TaxPriceAmount - row.CostAmount;
                                        //成本利润率
                                        if (row.CostAmount == 0) {
                                            row.CostProfitRate = 100;
                                        } else {
                                            row.CostProfitRate = row.Profit / row.CostAmount * 100;
                                        }

                                        //格式化(先计算，再格式化，不然数据不准)
                                        row.Amount = parseFloat(row.Amount).toFixed(2);
                                        row.CostAmount = parseFloat(row.CostAmount).toFixed(2);
                                        row.ContainTaxPrice = parseFloat(row.ContainTaxPrice).toFixed(2);
                                        row.TaxPrice = parseFloat(row.TaxPrice).toFixed(2);
                                        row.TaxPriceAmount = parseFloat(row.TaxPriceAmount).toFixed(2);
                                        row.Profit = parseFloat(row.Profit).toFixed(2);
                                        row.CostProfitRate = parseFloat(row.CostProfitRate).toFixed(2);
                                    }
                                }
                                else {
                                    $(this).val(0);
                                    $(this).showToastr("只能输入数字!");
                                }
                            });

                        }

                    }
                    else {
                        $($element).html(html);
                        var inputObj = $("#" + $(html).attr("id"));
                        inputObj.focus();
                        inputObj.select();
                        inputObj.bind("focusout", function () {
                            row[field] = $(this).val();
                            $("#ExchangeItems").bootstrapTable('updateRow', { index: index, row: row });
                            $($element).html("" + value + "");
                        });
                    }

                }
                else if (field == "Remark") {
                    //0元开单，必须选择备注
                    if (row.Price >= 0) {
                        var html = '<select name="' + field + '" id="' + field + "_" + row.Id + '">';
                        $.each(remarkConfigs, function (key, re) {
                            if (re.Id > 0) {
                                html += '<option value="' + re.Id + '"  ' + (row.Remark == re.Name ? "selected" : "") + '>' + re.Name + '</option>';
                            }
                        });

                        html += '</select>';

                        $($element).html(html);

                        var inputObj = $("#" + $(html).attr("id"));
                        inputObj.focus();
                        inputObj.select();
                        inputObj.bind("focusout", function () {
                            $($element).html("" + inputObj.find("option:selected").text() + "");
                            $("#ExchangeItems").bootstrapTable('updateRow', { index: index, row: { Remark: inputObj.find("option:selected").text() } });
                        });
                        inputObj.bind("change", function () {
                            //当前选择
                            var remark = $(this).find("option:selected").text();
                            $("#SaleItems").bootstrapTable('updateRow', { index: index, row: { Remark: remark } });
                        });
                    }
                    else {

                        var html = '<input type="text" class="form-control input-sm" value="' + (typeof (value) == 'undefined' ? "" : value) + '" id="' + field + "_" + row.Id + '">';
                        $($element).html(html);
                        var inputObj = $("#" + $(html).attr("id"));
                        inputObj.focus();
                        inputObj.select();
                        inputObj.bind("focusout", function () {
                            $("#ExchangeItems").bootstrapTable('updateRow', { index: index, row: { Remark: $(this).val() } });
                            $($element).html("" + value + "");
                        });
                    }
                }
                else if (field == "UnitName") {
                    console.log("Units:" + row.Units);

                    if (row.Units == null) {
                        $(this).showToastr('请选择商品');
                        return;
                    }

                    console.log("UnitId:" + row.UnitId);

                    var html = '<select name="' + field + '" id="' + field + "_" + row.Id + '">';
                    //var keys = Object.keys(row.Units);
                    $.each(row.Units, function (key, unit) {
                        if (unit > 0) {
                            html += '<option value="' + unit + '"  ' + (row.UnitId == unit ? "selected" : "") + '>' + key + '</option>';
                        }
                    });
                    html += '</select>';

                    $($element).html(html);

                    var inputObj = $("#" + $(html).attr("id"));
                    inputObj.focus();
                    inputObj.select();
                    inputObj.bind("focusout", function () {
                        console.log(row.UnitId + "=" + inputObj.val());
                        console.log(inputObj.find("option:selected").text());
                        $($element).html("" + inputObj.find("option:selected").text() + "");
                        //$("#ExchangeItems").bootstrapTable('updateRow', { index: index, row: { UnitName: inputObj.find("option:selected").text(),Units: row.Units } });
                        $("#ExchangeItems").bootstrapTable('updateRow', { index: index, row: { UnitName: inputObj.find("option:selected").text() } });
                    });

                    //单位选择
                    inputObj.bind("change", function () {
                        //alert("change");
                        //用户选择的价格体系
                        var defaultAmountId = $("#DefaultAmountId").val();
                        //用户当前选择的单位
                        var unitId = $(this).val();
                        //价格
                        var price = 0;
                        //金额
                        var amount = 0;
                        //成本价
                        var costPrice = 0;
                        //成本金额
                        var costAmount = 0;
                        var ck = Object.keys(row.CostPrices);
                        var cv = Object.values(row.CostPrices);
                        ck.forEach(function (a, b) {
                            if (a == unitId) {
                                costPrice = cv[b];
                            }
                        });

                        //判断用户当前选择的单位是小，中，大
                        var unitType = "SmallUnitId";
                        if (unitId == row.SmallUnitId) {
                            unitType = "SmallUnitId";
                        }
                        if (unitId == row.StrokeUnitId) {
                            unitType = "StrokeUnitId";
                        }
                        if (unitId == row.BigUnitId) {
                            unitType = "BigUnitId";
                        }

                        //先个给一个默认价格
                        row.Prices.forEach(function (a, b) {
                            if (a.UnitId == unitId) {
                                //price = a.ProductPrice.TradePrice;
                                costPrice = a.ProductPrice.CostPrice;
                            }
                        });

                        //如果此商品有价格体系
                        row.ProductTierPrices.forEach(function (a, b) {
                            var planIdTypeId = a.PricesPlanId + "_" + a.PriceTypeId;
                            if (defaultAmountId == planIdTypeId) {
                                if (unitType == "SmallUnitId") {
                                    price = a.SmallUnitPrice;
                                }
                                if (unitType == "StrokeUnitId") {
                                    price = a.StrokeUnitPrice;
                                }
                                if (unitType == "BigUnitId") {
                                    price = a.BigUnitPrice;
                                }
                            }
                        });

                        //如果不允许改价,则用商品批发价
                        if (row.IsAdjustPrice == false) {
                            if (unitType == "SmallUnitId") {
                                price = row.Prices[0].ProductPrice.TradePrice;
                            }
                            if (unitType == "StrokeUnitId") {
                                price = row.Prices[1].ProductPrice.TradePrice;
                            }
                            if (unitType == "BigUnitId") {
                                price = row.Prices[2].ProductPrice.TradePrice;
                            }
                        }

                        amount = parseFloat(parseFloat((row.Quantity == undefined || row.Quantity == "") ? "0" : row.Quantity) * parseFloat(price)).toFixed(2);
                        costAmount = parseFloat(parseFloat((row.Quantity == undefined || row.Quantity == "") ? "0" : row.Quantity) * parseFloat(costPrice)).toFixed(2);

                        $("#ExchangeItems").bootstrapTable('updateRow', { index: index, row: { UnitId: unitId, UnitName: inputObj.find("option:selected").text(), Units: row.Units, Price: price, Amount: amount, CostPrice: costPrice, CostAmount: costAmount } });

                    });

                }
                else if (field == "ManufactureDete") {
                    if (row.IsManufactureDete == true) {
                        var html = '<select class="form-control input-sm" name="' + field + '" id="' + field + "_" + row.Id + '">';
                        if (row.ProductTimes != null) {
                            $.each(row.ProductTimes, function (key, date) {
                                if (date > 0) {
                                    html += '<option value="' + date + '"  ' + (row.ManufactureDete == date ? "selected" : "") + '>' + key + '</option>';
                                }
                            });
                        }

                        html += '</select>';

                        $($element).html(html);

                        var inputObj = $("#" + $(html).attr("id"));
                        inputObj.focus();
                        inputObj.select();
                        inputObj.bind("focusout", function () {
                            console.log(row.ManufactureDete + "=" + inputObj.val());
                            console.log(inputObj.find("option:selected").text());
                            $($element).html("" + inputObj.find("option:selected").text() + "");
                            $("#ExchangeItems").bootstrapTable('updateRow', { index: index, row: { ManufactureDete: inputObj.find("option:selected").text() } });
                        });
                    }
                }
            }
        });

		//保存服务器
        var submitRemoteServer = function (items, showMessage, doAudit, callback, loadingButton)
        {
            if (!formValidator())
            {
				if (loadingButton != undefined) {
					loadingButton.stop();
				}
				return false;
			}
			var reg = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 ，判断正整数用/^[1-9]+[0-9]*]*$/

			//获取表格的所有内容行
			var allTableData = $('#ExchangeItems').bootstrapTable('getData');
			var accounts = $("#ExchangeItems_Partial_Form").find("input[name='CollectionAmount']");
			var flag = 0;
			var numFlag = 0;
			var accFlag = 0;
			var errMsg = "";
			$.each(allTableData, function (i, row) {
				if (Object.keys(row).length > 1) {
					var manDate = $("#selDate_" + i).val();
					if (row.ProductId == "" || row.Quantity == "" || (manDate == "" && row.IsManufactureDete == true))
						flag++;
					else if (!reg.test(row.Quantity))
						numFlag++;
					else if (!reg.test(row.Price))
						numFlag++;
					if (row.ProductId != "" && row.Quantity == "") {
						errMsg += "商品：" + row.ProductName + " 数量为0.";
					}
					if (row.ProductId != "" && row.Price == 0 && row.Remark == "") {
						errMsg += "商品：" + row.ProductName + " ,0元开单，必须选择备注.";
					}
				}

			});

			//商品验证
			if (errMsg != "") {
				if (loadingButton != undefined) {
					loadingButton.stop();
				}
				$(this).showToastr(errMsg);
				return false;
			}

			$.each(accounts, function (i, input) {
				if (isNaN($(input).val()))
					accFlag++;
			});
			if (flag == allTableData.length) {
				if (loadingButton != undefined) {
					loadingButton.stop();
				}
				$(this).showToastr("请先填写单据明细!");
				return false;
			}
			else if (numFlag > 0) {
				if (loadingButton != undefined) {
					loadingButton.stop();
				}
				$(this).showToastr("数量只能输入数字!");
				return false;
			}

			var serializeData = [];
			var accountingOption = { AccountingOptionId: 0, CollectionAmount: 0 };
			var accountings = [];
            $.each(allTableData, function (i, row)
            {
				var tmpObj = {
					"Id": typeof (row.Id) == 'undefined' ? "0" : row.Id,
					"ProductId": typeof (row.ProductId) == 'undefined' ? "0" : row.ProductId,
					"UnitId": typeof (row.UnitId) == 'undefined' ? "0" : row.UnitId,
					"Quantity": typeof (row.Quantity) == 'undefined' ? "0" : row.Quantity,
					"Price": typeof (row.Price) == 'undefined' ? "0" : row.Price,
					"Amount": typeof (row.Amount) == 'undefined' ? "0" : row.Amount,
					"CostPrice": typeof (row.Price) == 'undefined' ? "0" : row.CostPrice,
					"CostAmount": typeof (row.Amount) == 'undefined' ? "0" : row.CostAmount,
					"StockQty": typeof (row.StockQty) == 'undefined' ? "0" : row.StockQty,
					"RemainderQty": typeof (row.RemainderQty) == 'undefined' ? "0" : row.RemainderQty,
					"Remark": typeof (row.Remark) == 'undefined' ? "" : row.Remark,
					"ManufactureDete": typeof (row.ManufactureDete) == 'undefined' ? "" : row.ManufactureDete,
                    "IsGifts": typeof (row.IsGifts) == 'undefined' ? false : row.IsGifts,
					"SaleProductTypeId": typeof (row.SaleProductTypeId) == 'undefined' ? "0" : row.SaleProductTypeId,
					"GiveTypeId": typeof (row.GiveTypeId) == 'undefined' ? "0" : row.GiveTypeId,
					"CampaignId": typeof (row.CampaignId) == 'undefined' ? "0" : row.CampaignId,
					"CampaignBuyProductId": typeof (row.CampaignBuyProductId) == 'undefined' ? "0" : row.CampaignBuyProductId,
					"CampaignGiveProductId": typeof (row.CampaignGiveProductId) == 'undefined' ? "0" : row.CampaignGiveProductId,
					"CampaignLinkNumber": typeof (row.CampaignLinkNumber) == 'undefined' ? "" : row.CampaignLinkNumber,
					"CostContractId": typeof (row.CostContractId) == 'undefined' ? "0" : row.CostContractId,
					"CostContractItemId": typeof (row.CostContractItemId) == 'undefined' ? "0" : row.CostContractItemId,
					"CostContractMonth": typeof (row.CostContractMonth) == 'undefined' ? "0" : row.CostContractMonth,
					"IsFlavorProduct": typeof (row.IsFlavorProduct) == 'undefined' ? false : row.IsFlavorProduct,
					"FlavorId": typeof (row.FlavorId) == 'undefined' ? "" : row.FlavorId,
					"TaxRate": typeof (row.TaxRate) == 'undefined' ? "0" : row.TaxRate,
					"ContainTaxPrice": typeof (row.ContainTaxPrice) == 'undefined' ? "0" : row.ContainTaxPrice

				};
				serializeData.push(tmpObj);
			});

			//保存的数据
			var postData = {
				//客户
				TerminalId: $("#TerminalId").val(),
				//业务员
				BusinessUserId: $("#BusinessUserId").val(),
				//仓库
				WareHouseId: $("#WareHouseId").val(),
				//送货员
				//DeliveryUserId: $("#DeliveryUserId").val(),
				//付款方式
				PayTypeId: $("#PayTypeId").val(),
				//交易日期
				TransactionDate: $("input[name='TransactionDate']").val(),
				//按最小单位销售
				IsMinUnitSale: $("#IsMinUnitSale").val(),
				//备注
				Remark: $("#Remark").val(),
				//价格体系
				DefaultAmountId: $("#DefaultAmountId").val(),
				//优惠金额
				PreferentialAmount: 0,
				//优惠后金额
				PreferentialEndAmount: 0,
				//待支付金额
				OweCash: $("#OweCash").val(),
				//商品项目
				Items: serializeData,
				//收款账户
				Accounting: accountings,
				//预收金额
				AdvanceAmount: 0,
                //预收款余额
                AdvanceAmountBalance: 0
			};

			errMsg = "";
			//loadingButton.stop();
			//console.log(postDat);
			if (errMsg != "") {

                WinMsg.confirm({ message: errMsg + ",确认要开单吗？" }).on(function (e)
                {
					if (!e) {
						if (loadingButton != undefined) {
							loadingButton.stop();
						}
						return;
					}
                    $(this).remoteSubmit("post", "/ExchangeBill/CreateOrUpdate?billId=@(Model.Id)&doAudit=" + doAudit, postData, items, callback, showMessage, loadingButton);//
				});
			}
            else
            {
                $(this).remoteSubmit("post", "/ExchangeBill/CreateOrUpdate?billId=@(Model.Id)&doAudit=" + doAudit, postData, items, callback, showMessage, loadingButton);//
			}
		}

		//保存单据项目
        $("#FormSubmit").click(function ()
        {
            var doAudit = true;
			//防止重复保存
			var loadingButton = Ladda.create(this);
			loadingButton.start();

			//提交
            submitRemoteServer(null, null, doAudit,function (data)
            {
                if (data.Success)
                {
					  window.location.href = "/ExchangeBill/List";
                }
            }, loadingButton);
		});

		//保存并继续
        $("#FormSubmitContinue").click(function () {
            var doAudit = false;
			//防止重复保存
			var loadingButton = Ladda.create(this);
			loadingButton.start();
			if ("@Model.Id" == "0") {
                submitRemoteServer(null, null, doAudit,function () { window.location.href = "/ExchangeBill/Create"; }, loadingButton);
			} else {
                submitRemoteServer($("#ExchangeItems"), null, doAudit, function () { window.location.href = "/ExchangeBill/Edit/" + "@Model.Id"; }, loadingButton);
			}

		});

		/*
		 * ======================================================
		 * mschen 2018-12-5 11:24:43 end
		 * ======================================================
		 */
	});

</script>

